# coding=utf-8

import sys
import datetime

from builtins import int

sys.path.append("..")
from common.mysql.connect import MysqlConnector
from common.redis.connect import RedisConnector
from common.utils.time import get_yesterday_date
from common.utils.time import turn_date_to_ts
from models.manager import get_dict_of_mid_and_bid
from logic.cus_logic import CustomerLogic


def customer_buy_info(mysql, goods_id, date):
    """ 助理号每天销售信息汇总
    """
    # 根据时间戳获取当天的开始和结束时间戳，作为基准
    ts_start = turn_date_to_ts(date)
    ts_end = ts_start + 60 * 60 * 24 - 1

    # 实例化客户数据处理逻辑
    cus_logic = CustomerLogic()

    goods_sale_res = cus_logic.get_customer_buy_info(mysql, goods_id, ts_start, ts_end)
    goods_inlay_sale_res = cus_logic.get_customer_inlay_info(mysql, goods_id, ts_start, ts_end)
    goods_sale_res.extend(goods_inlay_sale_res)

    # 获取写数据的数据库连接实例
    mysql_db_data = MysqlConnector('data')

    sql_insert = "insert into customer_everyday_info (`customer_id`, `date`, `order_num`, `order_amount`,`inlay_num`," \
                 "`inlay_amount`,`refund_order_num`, `refund_order_amount`) values "

    if not goods_sale_res:
        return True
    else:
        # 当天有售出，汇总售出结果
        sale_num_amount = cus_logic.cal_sale_num_amount(goods_sale_res)
        sql_insert += " (%d, %d, %d, %f, %d, %f,%d, %f)  " % \
                      (goods_id, ts_start, sale_num_amount['order_num'], sale_num_amount['order_amount'],
                       sale_num_amount['inlay_num'],sale_num_amount['refund_order_num'],
                       sale_num_amount['refund_order_num'], sale_num_amount['refund_order_amount'])
    exec_res = mysql_db_data.execute(sql_insert)
    if not exec_res:
        return False
    return True


if __name__ == '__main__':
    """ 客户每日购买相关数据处理
    """
    # 获取要处理的日期
    if len(sys.argv) == 2:
        # 外部传递进来
        date = sys.argv[1]
    else :
        # 默认取前一天的日期
        date = datetime.datetime.strftime(get_yesterday_date(), "%Y-%m-%d")

    redis_14 = RedisConnector(14)
    mysql_db_order = MysqlConnector('order')

    while True:
        cus_id = redis_14.rpop('customer_id_list')

        if cus_id and (not redis_14.sismember('customer_list_' + date, cus_id)):
            res = customer_buy_info(mysql_db_order, int(cus_id), date)
            if res:
                redis_14.sadd('customer_list_' + date, cus_id)
            redis_14.lpush('customer_id_list', cus_id)
        else :
            print(date + "no more data")
            break
